package com.xudow.app.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.xudow.app.R;
import com.xudow.app.ui.task.user.FeedbackTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.util.HashMap;

/**
 * 新反馈Activity
 *
 * @author lukecheng
 */
public class FeedbackActivity extends BaseActivity {

    private EditText contentView;
    private EditText phoneView;

    private FeedbackTask feedbackTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);

        contentView = (EditText) findViewById(R.id.content);
        phoneView = (EditText) findViewById(R.id.phone);
    }

    /**
     * 提交按钮点击事件
     *
     * @param view
     */
    public void onSubmitClick(View view) {
        String content = contentView.getText().toString().trim();
        if (StringUtils.isEmpty(content)) {
            contentView.setError(getString(R.string.feedback_required));
            return;
        }

        String phone = phoneView.getText().toString().trim();

        HashMap<String, String> params = Maps.newHashMap();
        params.put("feedback", content);
        params.put("phone", phone);

        showLodingDialog(getString(R.string.processing));

        feedbackTask = new FeedbackTask(this, feedbackEditHandler);
        addTask(feedbackTask);
        feedbackTask.execute(params);
    }

    /**
     * 处理Handler
     */
    private Handler feedbackEditHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (FeedbackTask.SUCCESS == msg.what) {
                String successMsg = getString(R.string.feedback_success);
                Toast.makeText(FeedbackActivity.this, successMsg, Toast.LENGTH_LONG).show();

                contentView.setText("");
                phoneView.setText("");
            } else {
                String errMessage = getString(R.string.feedback_error);
                Toast.makeText(FeedbackActivity.this, errMessage, Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && null != feedbackTask
                && !feedbackTask.isCancelled()) {
            feedbackTask.cancel(true);
            feedbackTask = null;
        }

        return super.onKeyDown(keyCode, event);
    }

    public void onBackBtnClick(View view) {
        finish();
    }
}
